package com.xunqi.ad.index.adplan;

import com.xunqi.ad.index.IndexAware;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 索引实现类
 * @Created: with IntelliJ IDEA.
 * @author: 夏沫止水
 * @createTime: 2020-05-02 22:40
 **/

@Slf4j
@Component
public class AdPlanIndex implements IndexAware<Long,AdPlanObject> {

    private static Map<Long,AdPlanObject> objectMap;

    static {
        objectMap = new ConcurrentHashMap<>();
    }

    /**
     * 通过K去获取索引
     * @param key
     * @return
     */
    @Override
    public AdPlanObject get(Long key) {
        return objectMap.get(key);
    }

    /**
     * 添加索引
     * @param key
     * @param value
     */
    @Override
    public void add(Long key, AdPlanObject value) {

        log.info("before add:{}",objectMap);
        objectMap.put(key,value);
        log.info("after add:{}",objectMap);

    }

    /**
     * 更新索引
     * @param key
     * @param value
     */
    @Override
    public void update(Long key, AdPlanObject value) {

        log.info("before update:{}",objectMap);
        //更新之前，根据原来的key获取当前对象
        AdPlanObject oldObject = objectMap.get(key);
        if (null == oldObject) {
            //如果不存在，就新增进去
            objectMap.put(key,value);
        } else {
            //更新操作
            oldObject.update(value);
        }

        objectMap.put(key,value);
        log.info("after update:{}",objectMap);

    }

    /**
     * 删除索引
     * @param key
     * @param value
     */
    @Override
    public void delete(Long key, AdPlanObject value) {

        log.info("before delete:{}",objectMap);
        objectMap.remove(key);
        log.info("before delete:{}",objectMap);

    }
}
